#!/bin/rc

# usage: pdfgsijs pdffile

gs -dSAFER -dNOPAUSE -dBATCH -q -s'DEVICE=pswrite' -d'LanguageLevel=2' -s'OutputFile=/tmp/pdf2ps.ps' $1

MODEL=`{echo $LPCLASS | sed 's/(.*\+)?gsijs!([^+]*)(\+.*)?/\2/'}
NUMBER=`{echo $LPCLASS | sed 's/(.*\+)?gsijs!([^+]*)\+(.*)?/\3/'}

GSTMPFILE=/tmp/pdf^$pid

switch($NUMBER) {
case 2100
	GSOPT=(-q -sDEVICE'='ijs -sIjsServer'='hpijs -sDeviceManufacturer'='HP '-sDeviceModel='"$MODEL^' '^$NUMBER" -r600 -sOutputFile'='^$GSTMPFILE  -sPAPERSIZE'='a4 -dIjsUseOutputFD -dSAFER -dNOPAUSE -dBATCH)
case 2500
	GSOPT=(-q -sDEVICE'='ijs -sIjsServer'='hpijs -sDeviceManufacturer'='HP '-sDeviceModel='"$MODEL^' '^$NUMBER" -r600 -sOutputFile'='^$GSTMPFILE -dDuplex'='true -sPAPERSIZE'='a4 -dIjsUseOutputFD -dSAFER -dNOPAUSE -DBATCH)
}


if(~ $OLIST '')
	gs $GSOPT /tmp/pdf2ps.ps
if not {
	PGLIST=`{echo $OLIST | sed 's/-o//;s/,/ /g;s/	/ /g' | tr -cd '0-9 -'}
	GSPGLIST=()
	for(i in $PGLIST){
		switch($i){
		case -*
			GSPGLIST=($GSPGLIST `{seq 1 `{echo $i|tr -d '-'}})
		case *-
			# BUG assume 100 >= number of pages
			GSPGLIST=($GSPGLIST `{seq `{echo $i|tr -d '-'} 100})
		case *-*
			GSPGLIST=($GSPGLIST `{seq `{echo $i|tr '-' ' '}})
		case *
			GSPGLIST=($GSPGLIST $i)
		}
	}
	GSPGLIST=$"GSPGLIST
	echo '
		/Page null def
		/Page# 0 def
		/PDFSave null def
		/DSCPageCount 0 def
		/DoPDFPage {dup /Page# exch store pdfgetpage pdfshowpage} def
		GS_PDF_ProcSet begin
		pdfdict begin
		('^$1^') (r) file pdfopen begin
		/npage pdfpagecount def
		['^$GSPGLIST^']
		{
			dup dup
				1 ge exch npage le and 
				{ DoPDFPage }
				{ pop }
			ifelse
		} forall
	' | gs $GSOPT - >/dev/null >[2=1]
}

cat $GSTMPFILE
rm -f $GSTMPFILE
rm -f /tmp/pdf2ps.ps
exit ''
